//
//  SHPPictureView.swift
//  weibo
//
//  Created by songhuipan on 16/4/22.
//  Copyright © 2016年 songhuipan. All rights reserved.
//

import UIKit
private let itemMargin:CGFloat = 5
private let itemWH:CGFloat = (kScreenWidth - 20 - itemMargin*2) / 3
private let pictureCollectionViewCell = "pictureCollectionViewCell"

class SHPPictureView: UICollectionView {
    
    var pic_urls:[SHPPic_urls]? {
        
        didSet {
            
            let size = getCollectionViewSize(pic_urls?.count ?? 0)
            
            // 更改自己的约束 没有涉及到被人来约束的 需要使用update 更简单
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
            self.reloadData()
        }
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

}
extension SHPPictureView {
/// 设置collectionView中的控件
    func setupUI () {
        
        backgroundColor = UIColor.clearColor()
        
        dataSource = self
        delegate = self
        
        registerClass(SHPPictureCollectionViewCell.self, forCellWithReuseIdentifier: pictureCollectionViewCell)
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        layout.itemSize = CGSizeMake(itemWH, itemWH)
        
        
    }
    /// 根据图片数组个数返回collectionView大小的方法
    ///
    /// - parameter pic_urlsCount: 图片数组个数
    ///
    /// - returns: collectionView的大小
    func getCollectionViewSize(pic_urlsCount:Int) ->CGSize {
        
        let col = pic_urlsCount >= 3 ? 3 :pic_urlsCount
        let row = (pic_urlsCount - 1)/3+1
        
        let width = CGFloat(col)*itemWH + CGFloat(col - 1)*itemMargin
        let height = CGFloat(row)*itemWH + CGFloat(row - 1)*itemMargin
        
        
        return CGSizeMake(width, height)
        
    }
}
/// UICollectionViewDataSource
extension SHPPictureView:UICollectionViewDataSource ,UICollectionViewDelegate{
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pic_urls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCollectionViewCell, forIndexPath: indexPath) as! SHPPictureCollectionViewCell
        
        cell.picInfo = pic_urls?[indexPath.item]
        
//        print(pic_urls)
        
        return cell
    }
    // MARK:实现代理方法，实现点击图片放大，浏览功能
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = (pic_urls?.count)!
        photoBrowser.sourceImagesContainerView = self
        
        photoBrowser.show()
    }
        
}
// MARK:浏览 图片的代理方法
extension SHPPictureView:SDPhotoBrowserDelegate {
    
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = cellForItemAtIndexPath(indexPath) as! SHPPictureCollectionViewCell
        
        return cell.backgroundImageView.image
    }
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = (self.pic_urls![index].thumbnail_pic ?? "" as NSString).stringByReplacingOccurrencesOfRegex("thumbnail_pic", withString: "bmiddle")
        
        return NSURL(string: urlString)
    }
    
}
/// SHPPictureCollectionViewCell类
class SHPPictureCollectionViewCell:UICollectionViewCell {
    
    var picInfo:SHPPic_urls? {
        didSet {
            backgroundImageView.sd_setImageWithURL(NSURL(string: (picInfo?.thumbnail_pic) ?? ""), placeholderImage: UIImage(named: "timeline_card_top_background"))

            if let bg = picInfo?.thumbnail_pic where bg.hasSuffix(".gif"){
                gifImageView.hidden = false
                
//                print(picInfo)
            }else {
                gifImageView.hidden = true
            }
            
        }
        
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI () {
        backgroundColor = UIColor.whiteColor()
        
        addSubview(backgroundImageView)
        addSubview(gifImageView)
        backgroundImageView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView).offset(UIEdgeInsetsZero)
        }
        gifImageView.snp_makeConstraints { (make) -> Void in
            make.trailing.bottom.equalTo(contentView)
        }
        
    }
    // MARK:懒加载背景图片
    private lazy var backgroundImageView :UIImageView = {
        let backgroundImageView = UIImageView(image: UIImage(named: "timeline_card_top_background"))
        
        backgroundImageView.contentMode = .ScaleAspectFill
        
        backgroundImageView.clipsToBounds = true
        
        return backgroundImageView
    
    }()
    // MARK:懒加载动态图片logo
    private lazy var gifImageView :UIImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
}



























